<?php
namespace app\controller;

use app\BaseController;
use app\validate\CheckChangeAmount;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;
use Carbon\Carbon;


// 积分记录
class IntegralRecord extends BaseController
{
    public function task()
    {
        return View::fetch();
    }


    // 任务明细数据
    public function getTaskRecordList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->param();


        if (isset($get['field']) && isset($get['order'])) {
            if (!empty($get['field']) && !empty($get['order'])) {
                $field = $get['field'];
                $sort = $get['order'];
                $where = session('task_record_where');
                $where1 = session('task_record_where1');
            } else {
                $field = 'id';
                $sort = 'desc';
                $where = session('task_record_where');
                $where1 = session('task_record_where1');
            }
        } else {
            $field = 'id';
            $sort = 'desc';
            $where = [];
            $where1 = [];
            if (isset($get['title'])) {
                if (!empty($get['title'])) {
                    $where[] = ['a.title', 'like', '%'.$get['title'].'%'];
                }
            }


            if (isset($get['time'])) {
                if (!empty($get['time'])) {
                    $t = explode(' - ', $get['time']);
                    $where1[] = ['add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
                }
            }
            session('task_record_where', $where);
            session('task_record_where1', $where1);
        }


        $total = Db::table('o_integral_task')
            ->alias('a')
            ->where($where)
            ->count();


        // 参与人数
        $subQuery = Db::table('o_integral_detail')
            ->distinct(true)
            ->field('count(distinct uid) as user_count, task_id')
            ->where($where1)
            ->group('task_id')
            ->buildSql();

        // 参与人次
        $subQuery1 = Db::table('o_integral_detail')
            ->field('task_id, count(id) as num_count')
            ->where($where1)
            ->group('task_id')
            ->buildSql();

        // 奖励总积分
        $subQuery2 = Db::table('o_integral_detail')
            ->field('task_id, sum(integral) as integral_count')
            ->where($where1)
            ->group('task_id')
            ->buildSql();


        $rows = Db::table('o_integral_task')
            ->alias('a')
            ->join($subQuery.'b','a.id=b.task_id','left')
            ->join($subQuery1.'c','a.id=c.task_id','left')
            ->join($subQuery2.'d','a.id=d.task_id','left')
            ->field('a.id, a.title, a.type, b.user_count, c.num_count, d.integral_count')
            ->where($where)
            ->order("$field", "$sort")
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            if (empty($v['user_count'])) {
                $v['user_count'] = 0;
            }

            if (empty($v['num_count'])) {
                $v['num_count'] = 0;
            }

            if (empty($v['integral_count'])) {
                $v['integral_count'] = 0;
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'data'=> $rows,
            'count' => $total,
        );
        return json($data);
    }

    // 任务详情
    public function taskDetail(Request $request)
    {
        $task_id = $request->get('task_id');
        View::assign('task_id', $task_id);
        return View::fetch();
    }

    // 任务详情数据
    public function getTaskDetailList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        $where = [];
        $get = $request->param();
        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.userid|b.name', 'like', '%' . $get['key'] . '%'];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }


        $total = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_members b','a.uid = b.id','left')
            ->where('a.task_id', '=', $get['task_id'])
            ->where($where)
            ->count();

        $rows = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_members b','a.uid = b.id','left')
            ->where('a.task_id', '=', $get['task_id'])
            ->where($where)
            ->order('a.add_time', 'desc')
            ->field('b.userid, b.name, a.integral, a.add_time')
            ->page($get['page'], $get['limit'])
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 用户明细
    public function user()
    {
        $task = Db::name('integral_task')->where('status', '=', 1)->select()->toArray();
        View::assign('task', $task);
        return View::fetch();
    }

    // 用户明细数据
    public function getUserRecordList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->param();

        if (isset($get['field']) && isset($get['order'])) {
            if (!empty($get['field']) && !empty($get['order'])) {
                $field = $get['field'];
                $sort = $get['order'];
                $where = session('user_record_where');
            } else {
                $field = 'id';
                $sort = 'asc';
                $where = session('user_record_where');
            }
        } else {
            $field = 'id';
            $sort = 'asc';
            $where = [];
            if (isset($get['title'])) {
                if (!empty($get['title'])) {
                    $where[] = ['b.name|b.userid', 'like', '%'.$get['title'].'%'];
                }
            }


            if (isset($get['time'])) {
                if (!empty($get['time'])) {
                    $t = explode(' - ', $get['time']);
                    $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
                }
            }

            if (isset($get['task_id'])) {
                if (!empty($get['task_id'])) {
                    $where[] = ['a.task_id', '=', $get['task_id']];
                }
            }

            session('task_record_where', $where);
        }


        $total = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_members b','a.uid = b.id','left')
            ->join('o_integral c','c.userid = b.userid','left')
            ->group('a.uid')
            ->where($where)
            ->count();


        $rows = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_members b','a.uid = b.id','left')
            ->join('o_integral c','c.userid = b.userid','left')
            ->group('a.uid')
            ->where($where)
            ->field('a.id as aid, a.uid, b.id, b.userid, b.name, sum(a.integral) as get_num, sum(a.use_integral) as use_num, c.num as rest_num')
            ->order("$field", "$sort")
            ->page($get['page'], $get['limit'])
            ->select();


        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 学员详情
    public function userDetail(Request $request)
    {
        $uid = $request->get('uid');
        View::assign('uid', $uid);
        return View::fetch();
    }



    public function getUserDetailList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $where = [];
        $get = $request->param();

        if (isset($get['title'])) {
            if (!empty($get['title'])) {
                $where[] = ['b.intro|c.title|a.remark', 'like', '%'.$get['title'].'%'];
            }
        }

        if (isset($get['task_id'])) {
            if (!empty($get['task_id'])) {
                if ($get['task_id'] == 1) {
                    $where[] = ['a.remark', '=', ''];
                    $where[] = ['a.integral', '>', 0];
                }elseif ($get['task_id'] == 2){
                    $where[] = ['a.remark', '<>', ''];
                    $where[] = ['a.use_integral', '>', 0];
                }else {
                    $where[] = ['a.remark', '<>', ''];
                }
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }


        $total = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_integral_task b','a.task_id = b.id','left')
            ->join('o_integral_goods c','a.goods_id = c.id','left')
            ->where('a.uid', $get['uid'])
            ->where($where)
            ->count();

        $rows = Db::table('o_integral_detail')
            ->alias('a')
            ->join('o_integral_task b','a.task_id = b.id','left')
            ->join('o_integral_goods c','a.goods_id = c.id','left')
            ->where('a.uid', $get['uid'])
            ->where($where)
            ->order('a.add_time', 'desc')
            ->field('b.intro, a.integral, a.use_integral, a.status, a.add_time, a.remark')
            ->page($get['page'], $get['limit'])
            ->select()->toArray();


        foreach ($rows as &$v) {
            if ($v['status'] == 0) {
                $v['integral'] =  '-'.$v['use_integral'];
                $v['status_info'] = '积分消耗';
                $v['intro_info'] = $v['remark'];
            } elseif ($v['status'] == 1) {
                $v['status_info'] = '积分获取';

                if ($v['intro']) {
                    $v['intro_info'] = $v['intro'];
                } else {
                    $v['intro_info'] = $v['remark'];
                }
            }else{
                $v['status_info'] = '其他';
                $v['intro_info'] = $v['remark'];
            }
        }


        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    //积分调整
    public function changeAmount(Request $request)
    {
        $uid = $request->param('uid');

        $inf = Db::table('o_members')
            ->alias('a')
            ->join('o_integral b','a.userid = b.userid','left')
            ->where('a.id', $uid)
            ->field('a.id, a.name, a.userid, b.num')
            ->find();
        View::assign('inf',$inf);
        return View::fetch();
    }



    public function changeModify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckChangeAmount::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        $id = $post['id'];
        $score = $post['score'];
        $remark = $post['remark'];
        if ($score == 0) {
            return $this->outputAjax('调整分不能为0');
        }

        if ($score > 0) {
            try {
                Db::transaction(function() use($id,$score,$remark) {
                    $userid = Db::table('o_members')->where('id',$id)->value('userid');
                    $user_integral_info = Db::table('o_integral')->where('userid',$userid)->find();
                    //1生成购买记录2给用户减积分3给商品加购买记录
                    Db::table('o_integral_detail')->insert([
                        'uid' => $id,
                        'userid' => $userid,
                        'integral' => $score,
                        'add_time' => time(),
                        'add_at' => Carbon::now()->toDateString(),
                        'status' => 1,
                        'remark' => $remark,
                    ]);
                    Db::table('o_integral')->where('id',$user_integral_info['id'])->inc('num', $score)->update();
                });
                return $this->outputAjax('操作成功！',0);
            }catch(\Exception $e)
            {
                return $this->outputAjax($e->getMessage());

            }
        }else{
            try {
                Db::transaction(function() use($id,$score,$remark) {
                    $score = abs($score);
                    $userid = Db::table('o_members')->where('id',$id)->value('userid');
                    $user_integral_info = Db::table('o_integral')->where('userid',$userid)->find();
                    if ($user_integral_info['num'] < $score) {
                        throw new \Exception('余额不足');
                    }
//                    $no = date('YmdHis').str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
                    //1生成购买记录2给用户减积分3给商品加购买记录
                    Db::table('o_integral_detail')->insert([
                        'uid' => $id,
                        'userid' => $userid,
                        'use_integral' => $score,
                        'add_time' => time(),
                        'add_at' => Carbon::now()->toDateString(),
                        'status' => 0,
                        'remark' => $remark,
                    ]);
                    Db::table('o_integral')->where('id',$user_integral_info['id'])->dec('num', $score)->update();
                });
                return $this->outputAjax('操作成功！',0);
            }catch(\Exception $e)
            {
                return $this->outputAjax($e->getMessage());

            }
        }
    }


    public function import()
    {
        return View::fetch();
    }


    public function executeImport(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');
        // 获取excel表格数据
        $result = get_excel_info($filename);
        if ($result['code'] == 1) {
            return $this->outputAjax($result['msg'], 2);
        }
        Db::startTrans();

        try {

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];
                $integral = $value[1];
                $remark = $value[2];

                $user = Db::name('members')->where('userid', '=', $userid)->find();
                if ($user) {
                    $user_integral_info = Db::name('integral')->where('userid', '=', $userid)->find();
                    if ($user_integral_info) {
                        $insert = [
                            'uid' => $user['id'],
                            'userid' => $user['userid'],
                            'integral' => $integral,
                            'add_time' => time(),
                            'add_at' => Carbon::now()->toDateString(),
                            'status' => 1,
                            'remark' => $remark,
                        ];

                        $res = Db::name('integral_detail')->insert($insert);
                        if (!$res) {
                            Db::rollback();
                        }
                        if (!Db::name('integral')->where('id', '=', $user_integral_info['id'])->inc('num', $integral)->update()) {
                            Db::rollback();
                        }
                        $i++;
                    }
                }
            }
            Db::commit();
            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage(), 2);
        }
    }

    public function import1()
    {
        return View::fetch();
    }


    public function executeImport1(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');
        // 获取excel表格数据
        $result = get_excel_info($filename);
        if ($result['code'] == 1) {
            return $this->outputAjax($result['msg'], 2);
        }
        Db::startTrans();
        try {

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];
                $integral = $value[1];
                $remark = $value[2];

                $user = Db::name('members')->where('userid', '=', $userid)->find();
                if ($user) {
                    $user_integral_info = Db::name('integral')->where('userid', '=', $userid)->find();
                    if ($user_integral_info['num'] < $integral) {
                        continue;
                    } else {
                        if ($user_integral_info) {
                            $insert = [
                                'uid' => $user['id'],
                                'userid' => $user['userid'],
                                'use_integral' => $integral,
                                'add_time' => time(),
                                'add_at' => Carbon::now()->toDateString(),
                                'status' => 0,
                                'remark' => $remark,
                            ];
                            $res = Db::name('integral_detail')->insert($insert);
                            if (!$res) {
                                Db::rollback();
                            }

                            if (!Db::name('integral')->where('id', '=', $user_integral_info['id'])->dec('num', $integral)->update()) {
                                Db::rollback();
                            }
                            $i++;
                        }
                    }
                }
            }
            Db::commit();
            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
            
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage(), 2);
        }
    }
}